import {
  login,
  getResource
} from '@/api/login'
import {
  logout
} from '@/api/logout'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter,
  constantRoutes,
  notFoundRouter
} from '@/router'
import routerFormat from '@/router/filterRouter'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '', // 头像
    roles: [], // 角色
    routers: constantRoutes, // 路由集
    addRouters: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTERS: (state, routers) => {
    state.addRouters = routers; //路由访问
    state.routers = constantRoutes.concat(routers).concat(notFoundRouter); //加入菜单项,404路由最后加入
  }
}

const actions = {
  // 登录
  login({
    commit
  }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        if (response.code == 200) {
          // 获取token
          const token = response.data
          commit('SET_TOKEN', token)
          setToken(token)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getResource({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      // 获取用户信息
      getResource().then(response => {
        if (response.code == 200) {
          const data = response.data
          if (!data) {
            reject('验证失败，请重新登录')
          }

          commit('SET_NAME', data.username)
          commit('SET_AVATAR', data.avatar)

          commit('SET_ROUTERS', routerFormat(data.routers))
          resolve(response)
        } else {
          console.error(response)
          reject(response)
        }
      }).catch(error => {
        console.error(error)
        reject(error)
      })

    })
  },

  // 退出登录
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        // 必须先删除令牌
        removeToken()

        // 重置路由
        resetRouter()
        // 重置数据
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },


  // remove token
  removeToken({
    commit
  }) {
    return new Promise(resolve => {
      // 必须先删除令牌
      removeToken()
      // 重置数据
      commit('RESET_STATE')
      resolve()
    })
  },

  // refresh token
  refreshToken({
    commit
  }, newToken) {
    return new Promise(resolve => {
      // 必须先删除令牌
      removeToken()

      // 重新设置token
      commit('SET_TOKEN', newToken)
      setToken(newToken)

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
